#pragma once

#include <string>
#include <unistd.h>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cctype>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "log.hpp"
#include "protocol.hpp"

namespace Client
{

    const int BUFFER_SIZE = 1024;

    enum
    {
        USAGE_ERROR = 1,
        SOCKET_ERROR,
        CONNECT_ERROR
    };

    //切割输入操作数据和操作符
    bool cutMesage(std::string& line, Request* request);

    class TcpClient
    {
    public:
        TcpClient(const std::string& ServerIp, const uint16_t& ServerPort)
            : _sockfd(-1), _ServerPort(ServerPort), _ServerIp(ServerIp)
        {}

        ~TcpClient()
        {
            if (_sockfd >= 0)
                close(_sockfd);
        }

        void init()
        {
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                std::cerr << "socket error" << std::endl;
                exit(SOCKET_ERROR);
            }
        }

        void start()
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(_ServerIp.c_str());
            server.sin_port = htons(_ServerPort);
            if (connect(_sockfd, (const sockaddr*)&server, sizeof(server)) != 0)
            {
                std::cerr << "connect error" << std::endl;
                exit(CONNECT_ERROR);
            }
            else
            {
                std::string mesg;
                std::string inbuff;
                // char buffer[BUFFER_SIZE] = "";
                while (true)
                {
                    std::cout << "请输入( x operator y )>: ";
                    std::getline(std::cin, mesg);

                    // 切割输入
                    Request req;
                    if (!cutMesage(mesg, &req))
                    {
                        std::cerr << "输入错误" << std::endl;
                        continue;
                    }

                    // 请求
                    //序列化
                    std::string request_masage;
                    req.serialize(&request_masage);
                    //添加报头
                    std::string send_masage = enLenth(request_masage);
#ifdef DEBUG
                    std::cout << send_masage << std::endl;
#endif
                    //发送信息
                    send(_sockfd, send_masage.c_str(), send_masage.size(), 0);
#ifdef DEBUG
                    std::cout << "发送成功" << std::endl;
#endif
                    //响应
                    std::string package, resp_masage;
                    if (!recvPackge(_sockfd, inbuff, &package))
                        continue;
                    if (!deLenth(package, &resp_masage))
                        continue;

                    Response resp;
                    resp.deserialize(resp_masage);

                    std::cout << "eixtcode: " << resp._exitcode << std::endl;
                    std::cout << "result: " << resp._result << std::endl;

                    // int n = read(_sockfd, buffer, sizeof(buffer)-1);
                    // if (n > 0)
                    // {
                    //     buffer[n] = 0;
                    //     std::cout << "server回复 # " << buffer << std::endl;
                    // }
                    // else 
                    // {
                    //     break;
                    // }
                }
            }
        }

    private:
        int _sockfd;
        uint16_t _ServerPort;
        std::string _ServerIp;

    };
}

bool Client::cutMesage(std::string& line, Request* request)
{    
    size_t pos = line.find_first_of("+-*/%");
    if (pos == std::string::npos)
        return false;
    if ( (!line.find_first_not_of("0123456789 ", 0, pos + 1)) || (!line.find_first_not_of("0123456789 ", pos + 1)) )
        return false;

    std::string left, right;

    for (size_t i = 0; i < pos; ++i)
    {
        if (isdigit(line[i]))
            left += line[i];
    }

    for (size_t i = pos + 1; i < line.size(); ++i)
    {
        if (isdigit(line[i]))
            right += line[i];
    }

    request->_x = std::stoi(left);
    request->_y = std::stoi(right);
    request->_op = line[pos];

#ifdef DEBUG

    std::cout << request->_x << " " << request->_y << " " << request->_op << std::endl;

#endif

    return true;
}